package com.hyts.infodb.zuul.locator;

import com.hyts.infodb.zuul.service.ZuulService;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.util.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.RefreshableRouteLocator;
import org.springframework.cloud.netflix.zuul.filters.SimpleRouteLocator;
import org.springframework.cloud.netflix.zuul.filters.ZuulProperties;

import java.text.DateFormat;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @project-name:infodb
 * @package-name:com.hyts.infodb.zuul.locator
 * @author:Libo/Alex
 * @create-date:2019-05-21 21:31
 * @copyright:libo-hyts-github
 * @email:libo2dev@aliyun.com
 * @description:此类主要用于: 定制化的路由定位器-支持可刷新
 */
@Slf4j
public class CustomRouteLocator extends SimpleRouteLocator implements RefreshableRouteLocator {


    private ZuulProperties zuulProperties;

    @Getter
    @Setter
    ZuulService zuulService;



    public CustomRouteLocator(String servletPath, ZuulProperties properties) {
        super(servletPath, properties);
        this.zuulProperties = properties;
        addPathFrefixSeparator(this.zuulProperties.getPrefix());
        log.info("servletPath:{}",servletPath);
    }

    /**
     * 刷新操作
     */
    @Override
    public void refresh() {
        super.getRoutesMap().putAll(locateRoutes());
    }


    @Override
    protected Map<String, ZuulProperties.ZuulRoute> locateRoutes() {
        Map<String, ZuulProperties.ZuulRoute> routeData = new LinkedHashMap<>();
        routeData.putAll(super.locateRoutes());
        routeData.putAll(loadRouteByDB());
        //对总体route进行控制修改
        routeData.forEach((k,v)->{
            addPathFrefixSeparator(k);
        });
        return routeData;
    }

    /**
     * 获取Route信息从数据库中
     * @return
     */
    protected Map<String, ZuulProperties.ZuulRoute> loadRouteByDB(){
        return zuulService.findAllRoute().parallelStream().collect(Collectors.toMap
                (ZuulProperties.ZuulRoute::getPath,param->param));
    }


    protected void addPathFrefixSeparator(String path){
        path = path.startsWith("/")?path:"/"+path;
    }

}
